package com.example.listviewtest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private String[] data={"aaa","bbbb","ccc","ddd","eee","fff","ggg","hhh","iii","jjj"};
    private List<Fruit> fruitList=new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //加载普通适配器
//        ArrayAdapter <String> adapter=new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,data);


        //加载自定义适配器
        intiFruits();
        FruitAdapter adapter=new FruitAdapter(MainActivity.this,R.layout.fruit_item,fruitList);

        ListView listView=findViewById(R.id.list_view);
        listView.setAdapter(adapter);

        //添加点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Fruit fruit=fruitList.get(position);
                Toast.makeText(MainActivity.this,fruit.getName(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    //初始化水果数据
    private void intiFruits(){
        for(int i=0;i<10;i++){
            Fruit apple=new Fruit("Apple"+i,R.drawable.apple_pic);
            fruitList.add(apple);
            Fruit banana=new Fruit("Banana"+i,R.drawable.banana_pic);
            fruitList.add(banana);
        }
    }
}
